<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 收藏
 *
 * @author      Eden
 * @datetime    2016/12/18 22:20
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Collect_Model extends API_Model
{
    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主程序
     * @param array $params
     */
    public function run($params = array())
    {
        $send['state'] = false;
        do {

            if (!$this->checkParams($params)) {
                $send['error'] = $this->getError();
                break;
            }

            $where = array(
                'userId' => $params['userId'],
                'goodsId' => $params['goodsId']
            );

            $db = clone($this->db);
            $q = $db->get_where('user_collect', $where);
            $row = $q->row_array();

            if ($params['action'] == 'cancel') {
                if (empty($row)) {
                    $send['error'] = '商品没有在收藏夹中';
                    break;
                }

                // 取消
                $this->db->where(array('userId' => $params['userId'], 'goodsId' => $params['goodsId']));
                $this->db->delete('user_collect');
                $affected = $this->db->affected_rows();
            } else {
                if (!empty($row)) {
                    $send['error'] = '商品已经在收藏夹中';
                    break;
                }
                // 添加
                $this->db->insert('user_collect', $where);
                $affected = $this->db->insert_id();
            }

            if ($affected) {
                $send['state'] = true;
                $send['data'] = array(
                    'msg' => $params['action'] == 'collect' ? '收藏成功' : '取消成功'
                );
            } else {
                $send['error'] = '操作失败';
            }

        } while(false);
        $this->output->send($send);
    }

    /**
     * 检查参数
     * @param $params
     * @return bool
     */
    private function checkParams($params)
    {
        if (empty($params['userId']) || empty($params['goodsId']) || empty($params['action'])) {
            $this->setError('参数错误');
            return false;
        }

        if (!in_array($params['action'], array('cancel', 'collect'))) {
            $this->setError('无效操作类型');
            return false;
        }

        return true;
    }

}
